package com.ziyueyuwen.xiniao.spi.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ziyueyuwen.xiniao.bean.homework.AnswerData;
import com.ziyueyuwen.xiniao.bean.homework.QuestionInfo;
import com.ziyueyuwen.xiniao.spi.QuestionTypeService;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

import static com.ziyueyuwen.xiniao.enums.QuestionTypeEnum.GROUP;

/**
 * @author jun 2018/12/18.
 */
public class GroupImpl implements QuestionTypeService {

    @Override
    public void saveAnswer(String answerData, Integer questionNum, QuestionInfo questionInfo, List<AnswerData> answerDataList) {
        if (questionInfo.getQuestionType() == GROUP) {
            JSONArray answerArr = JSON.parseArray(answerData);
            List<AnswerData> groupAnswerDataList = new ArrayList<>();
            for (int i = 0; i < answerArr.size(); i++) {
                String tmpStr = answerArr.getString(i);
                ServiceLoader<QuestionTypeService> services = ServiceLoader.load(QuestionTypeService.class);
                for (QuestionTypeService q : services) {
                    q.saveAnswer(tmpStr, i + 1, questionInfo.getGroupList().get(i), groupAnswerDataList);
                }
            }
            int totalScore = 0;
            int correctScore = 0;
            for (AnswerData a : groupAnswerDataList) {
                totalScore += a.getTotalScore();
                correctScore += a.getCorrectScore();
            }
            AnswerData answerDataBean = new AnswerData();
            answerDataBean.setQuestionType(GROUP);
            answerDataBean.setTotalScore(totalScore);
            answerDataBean.setCorrectScore(correctScore);
            answerDataBean.setGroupAnswerDataList(groupAnswerDataList);
            if (answerDataList.size() < questionNum) {
                answerDataList.add(answerDataBean);
            } else {
                answerDataList.set(questionNum - 1, answerDataBean);
            }
        }
    }

}
